﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Text;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using LJLCommon.Helper;


namespace LJLNet
{
    public class SocketTCPPeer
    {
        private BaseThread mBaseThread;

        public ISocketListener mMono;

        public Socket mTcpSocket;

        public SocketTCPPeer(ISocketListener mono)
        {
            //创建socket  
            mTcpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            mMono = mono;
        }

        //连接服务器  
        public void Connect(string ip, int point)
        {
            if (mTcpSocket != null)
            {
                mTcpSocket.Connect(IPAddress.Parse(ip), point);
                if (mTcpSocket.Connected)
                {
                    mBaseThread = new ReceiveThread(this);
                    mBaseThread.Start();
                }
            }
        }

        //发送数据
        public void OnOperationRequest(byte operationType, Dictionary<byte, object> dataDict)
        {
            if (mTcpSocket != null && mTcpSocket.Connected)
            {
                string parameters = null;
                try
                {
                    parameters = DictToPackageHelper.Serializa(dataDict);
                }
                catch
                {
                    Debug.LogError("字典容器序列化失败");
                }

                if (!string.IsNullOrEmpty(parameters))
                {
                    mTcpSocket.Send(ASCIIEncoding.UTF8.GetBytes(parameters));
                }
            }
            else
            {
                Debug.Log("与服务器断开连接");
            }
        }

        //断开连接
        public void Disconnect()
        {
            if (mBaseThread != null)
            {
                mBaseThread.Stop();
            }
            if (mTcpSocket != null)
            {
                mTcpSocket.Close();
            }            
        }
    }
}
